<script lang="ts" setup>
// Register elements.
import "vidstack/player";
import "vidstack/player/ui";
import "vidstack/icons";
import {
  isHLSProvider,
} from "vidstack";
import type { MediaPlayerElement } from "vidstack/elements";

import type { MediaCanPlayEvent, MediaProviderChangeEvent } from "vidstack";
import VideoLayout from "./player-components/layouts/VideoLayout.vue";

const props = defineProps<{
  title?: string;
  src?: string;
  poster?: string;
  thumbnails?: string;
}>()
defineEmits<{
  videoEnd: [];
}>();
const playerElement = ref<MediaPlayerElement>();
// const vidMsg = defineModel<{ currentTime: number, duration: number }>();

// TODO: from [vid].vue
const videoSrc = useVideoConstant()

onMounted(() => {
  if (!playerElement.value)
    return
  for (const track of textTracks) playerElement.value.textTracks.add(track);
  // Subscribe to state updates - you can connect them to Vue refs if needed.
  return playerElement.value.subscribe(
    ({
      paused,
      viewType,
      bufferedStart,
      bufferedEnd,
      currentTime,
      duration,
    }) => {
      // console.log("start?", "->", bufferedStart);
      // console.log("end?", "->", bufferedEnd);
      // console.log("is paused?", "->", paused);
      // console.log("is audio view?", "->", viewType === "audio");
      // console.log("current time?", "->", currentTime);
      // vidMsg.value!.currentTime = currentTime;
      // vidMsg.value!.duration = duration;
      // console.log("duration?", "->", duration);
    },
  );
});

function onProviderChange(event: MediaProviderChangeEvent) {
  const provider = event.detail;
  // We can configure provider's here.
  if (isHLSProvider(provider))
    provider.config = {};
}

// We can listen for the `can-play` event to be notified when the player is ready.
function onCanPlay(event: MediaCanPlayEvent) {
  // ...
}
</script>

<template>
  <media-player
    ref="playerElement"
    class="w-full aspect-video bg-slate-900 text-white font-sans overflow-hidden rounded-md ring-media-focus data-[focus]:ring-4"
    :title="videoSrc.title"
    :src="props.src ?? videoSrc.src"
    crossorigin
    playsinline
    @provider-change="onProviderChange"
    @can-play="onCanPlay"
    @end="$emit('videoEnd')"
  >
    <media-provider>
      <media-poster
        cross-origin="anonymous" preload="auto"
        class="absolute inset-0 block h-full w-full rounded-md opacity-0 transition-opacity data-[visible]:opacity-100 [&>img]:h-full [&>img]:w-full [&>img]:object-cover"
        :src="props.src ?? videoSrc.poster"
        alt="The video"
      />
    </media-provider>
    <!-- 段落 -->
    <VideoLayout :thumbnails="videoSrc.thumbnails" />
  </media-player>
</template>

<style scoped>
*:not(:defined) {
  opacity: 0;
}
</style>
